package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import db.DBUtil;
import model.User;

public class UserDAO {
	public User getUser(String username,String password){
		User user = null;
		try {
			Connection conn = DBUtil.getConnection();
			PreparedStatement stmt = conn.prepareStatement("select * from users where username=? and passwords = ?");
			stmt.setString(1, username);
			stmt.setString(2, password);
			ResultSet rs = stmt.executeQuery();
			if(rs.next()){
				user = new User(rs.getInt("id"),rs.getString("username"),rs.getString("passwords"),rs.getInt("type"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}
	
	public boolean addUser(User user){
		try{
			Connection conn = DBUtil.getConnection();
			PreparedStatement stmt = conn.prepareStatement("insert into users (username,passwords,type) values(?,?,?)");
			stmt.setString(1, user.getUsername());
			stmt.setString(2, user.getPassword());
			stmt.setInt(3, user.getType());
			stmt.execute();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	public List<User> getStusAndTeas(){
		List<User> userList = new ArrayList<User>();
		try{
			Connection conn = DBUtil.getConnection();
			PreparedStatement stmt = conn.prepareStatement("select * from users where type = 2 or type = 3");
			ResultSet rs = stmt.executeQuery();
			while(rs.next()){
				User user = new User(rs.getInt("id"),rs.getString("username"),rs.getString("passwords"),rs.getInt("type"));
				userList.add(user);
			}
			return userList;
		}catch(Exception e){
			e.printStackTrace();
			return userList;
		}
	}
	
	public boolean deleteUser(int userid){
		try{
			Connection conn = DBUtil.getConnection();
			PreparedStatement stmt = conn.prepareStatement("delete from users where id = ?");
			stmt.setInt(1, userid);
			stmt.execute();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
}
